import React, { useState, useEffect, useRef, useContext } from 'react';
import {
    IonPage,
    IonContent,
    IonHeader,
    IonToolbar,
    IonButtons,
    IonMenuButton,
    IonTitle,
    IonSearchbar,
    IonSegment,
    IonSegmentButton,
    IonList,
    IonItem,
    IonThumbnail,
    IonLabel,
    IonNote,
    IonBadge,
    IonButton,
    IonIcon,
    IonFab,
    IonFabButton,
    IonModal,
    IonSelect,
    IonSelectOption,
    IonInput,
    useIonViewWillEnter
} from '@ionic/react';
import {
    heart,
    heartOutline,
    star,
    starOutline,
    bookmark,
    bookmarkOutline,
    search,
    add,
    trash,
    shareSocial,
    ellipsisHorizontal,
    time,
    folder,
    list,
    close
} from 'ionicons/icons';
import './SchedulePage.css';
import { platform, SqliteServiceContext, StorageServiceContext } from '../../App';
import { Toast } from '@capacitor/toast';
import { SQLiteDBConnection } from '@capacitor-community/sqlite';
import { ScheduleItem } from '../../models/ScheduleItem';


// 收藏项类型定义
type FavoriteType = 'all' | 'articles' | 'products' | 'places' | 'notes';

interface FavoriteItem {
    id: number;
    title: string;
    description: string;
    image: string;
    type: FavoriteType;
    tags: string[];
    date: string;
    rating: number;
    isFavorite: boolean;
}

// 分段按钮配置接口
interface SegmentButtonConfig {
    value: string;
    icon: string;
    label: string;
}

const SchedulePage: React.FC = () => {
    const [searchText, setSearchText] = useState('');
    const [selectedType, setSelectedType] = useState<string>('all');
    const [favorites, setFavorites] = useState<FavoriteItem[]>([]);
    const [filteredFavorites, setFilteredFavorites] = useState<FavoriteItem[]>([]);
    const [selectedTags, setSelectedTags] = useState<string[]>([]);
    const [allTags, setAllTags] = useState<string[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);


    const ref = useRef(false);
    const dbNameRef = useRef('');
    const isInitComplete = useRef(false);
    const [db, setDb] = useState<SQLiteDBConnection | null>(null);
    const sqliteServ = useContext(SqliteServiceContext);
    const storageServ = useContext(StorageServiceContext);
  
    const openDatabase = () => {
      try {
        const dbUsersName = storageServ.getDatabaseName();
        dbNameRef.current = dbUsersName;
        const version = storageServ.getDatabaseVersion();
  
        sqliteServ.openDatabase(dbUsersName, version, false).then((database) => {
          setDb(database);
          ref.current = true;
        });
      } catch (error) {
        const msg = `Error open database:: ${error}`;
        console.error(msg);
        Toast.show({
          text: `${msg}`,
          duration: 'long'
        });           
      }
    }
  
  
    useIonViewWillEnter( () => {
      const initSubscription = storageServ.isInitCompleted.subscribe((value) => {
        isInitComplete.current = value;
        if(isInitComplete.current === true) {
          const dbUsersName = storageServ.getDatabaseName();
          if(ref.current === false) {
            if(platform === "web") {
              window.addEventListener('beforeunload', (event) => {
      
                sqliteServ.closeDatabase(dbNameRef.current,false).then(() => {
                  ref.current = false;  
                })
                .catch((error) => {
                  const msg = `Error close database:: ${error}`;
                  console.error(msg);
                  Toast.show({
                    text: `${msg}`,
                    duration: 'long'
                  });           
                });
              });        
              customElements.whenDefined('jeep-sqlite').then(() => {
                openDatabase();
              })
              .catch ((error) => {
                const msg = `Error open database:: ${error}`;
                console.log(`msg`);
                Toast.show({
                  text: `${msg}`,
                  duration: 'long'
                });           
              });
  
            } else {
              openDatabase();
            }
          }
        }
      });
  
      return () => {
        initSubscription.unsubscribe();
      };
    }, [storageServ]);


    // 动态分段按钮配置
    const [segmentButtons, setSegmentButtons] = useState<SegmentButtonConfig[]>([]);

    // 添加新按钮模态框状态
    const [showAddModal, setShowAddModal] = useState(false);
    const [newButtonConfig, setNewButtonConfig] = useState<SegmentButtonConfig>({
        value: '',
        icon: bookmarkOutline,
        label: ''
    });

    const [newScheduleConfig,setNewScheduleConfig] = useState<ScheduleItem>({
        id : 0,
        description: "none",
        startDate: 0,
        endDate : 0,
        beginTime : 0,
        noticeMode : 0,
        repeatMode : 0,
    })

    //添加日程按钮模态框状态
    const [showAddScheduleModal, setShowAddScheduleModal] = useState(false)

    // 图标选项
    const iconOptions = [
        { value: list, label: '列表' },
        { value: bookmark, label: '书签' },
        { value: star, label: '星星' },
        { value: folder, label: '文件夹' },
        { value: time, label: '时间' },
        { value: heart, label: '心形' },
        { value: search, label: '搜索' }
    ];

    // 初始化分段按钮 - 从本地存储加载或使用默认值
    useEffect(() => {
        const savedButtons = localStorage.getItem('segmentButtons');
        if (savedButtons) {
            try {
                setSegmentButtons(JSON.parse(savedButtons));
            } catch (error) {
                console.error('加载分段按钮失败:', error);
                setDefaultButtons();
            }
        } else {
            setDefaultButtons();
        }
    }, []);

    // 设置默认按钮
    const setDefaultButtons = () => {
        const defaultButtons = [
            { value: 'all', icon: list, label: '全部' },
            { value: 'water', icon: bookmark, label: '喝水' },
            { value: 'sport', icon: star, label: '锻炼' },
            { value: 'food', icon: folder, label: '进食' },
            { value: 'work', icon: time, label: '工作' }
        ];
        setSegmentButtons(defaultButtons);
        saveButtonsToStorage(defaultButtons);
    };

    // 保存按钮配置到本地存储
    const saveButtonsToStorage = (buttons: SegmentButtonConfig[]) => {
        try {
            localStorage.setItem('segmentButtons', JSON.stringify(buttons));
        } catch (error) {
            console.error('保存分段按钮失败:', error);
        }
    };

    // 当segmentButtons变化时保存到本地存储
    useEffect(() => {
        if (segmentButtons.length > 0) {
            saveButtonsToStorage(segmentButtons);
        }
    }, [segmentButtons]);

    // 模拟加载收藏数据
    const loadFavorites = async () => {
        try {
            setIsLoading(true);
            // 从数据库获取数据
            const dbFavorites = await storageServ.getAllFavorites();
            // 转换数据格式
            const convertedFavorites: FavoriteItem[] = dbFavorites.map(item => ({
                id: item.id,
                title: item.title,
                description: item.description,
                image: item.image,
                type: item.type as FavoriteType,
                tags: item.tags.split(',').map(tag => tag.trim()),
                date: item.date,
                rating: item.rating,
                isFavorite: item.isFavorite === 1
            }));

            setFavorites(convertedFavorites);
            // 提取所有标签
            const tags = Array.from(new Set(convertedFavorites.flatMap(item => item.tags)));
            setAllTags(tags);
        } catch (error) {
            console.error('加载收藏数据失败:', error);
            setError('加载收藏数据失败，请重试');
            setFavorites([]);
            setAllTags([]);
        } finally {
            setIsLoading(false);
        }
    };


    // 页面加载时获取收藏数据
    useEffect(() => {
        loadFavorites();
    }, []);

    // 筛选收藏项
    useEffect(() => {
        let filtered = favorites;

        // 按类型筛选
        if (selectedType !== 'all') {
            filtered = filtered.filter(item => item.type === selectedType);
        }

        // 按搜索文本筛选
        if (searchText) {
            const searchLower = searchText.toLowerCase();
            filtered = filtered.filter(
                item =>
                    item.title.toLowerCase().includes(searchLower) ||
                    item.description.toLowerCase().includes(searchLower) ||
                    item.tags.some(tag => tag.toLowerCase().includes(searchLower))
            );
        }

        // 按标签筛选
        if (selectedTags.length > 0) {
            filtered = filtered.filter(item =>
                selectedTags.every(tag => item.tags.includes(tag))
            );
        }

        setFilteredFavorites(filtered);
    }, [favorites, selectedType, searchText, selectedTags]);

    // 切换收藏状态
    const toggleFavorite = (id: number) => {
        setFavorites(favorites.map(item =>
            item.id === id ? { ...item, isFavorite: !item.isFavorite } : item
        ));
    };

    // 切换标签选择
    const toggleTag = (tag: string) => {
        if (selectedTags.includes(tag)) {
            setSelectedTags(selectedTags.filter(t => t !== tag));
        } else {
            setSelectedTags([...selectedTags, tag]);
        }
    };

    // 清空所有筛选
    const clearFilters = () => {
        setSearchText('');
        setSelectedType('all');
        setSelectedTags([]);
    };

    // 打开添加新按钮模态框
    const openAddModal = () => {
        setNewButtonConfig({
            value: '',
            icon: bookmarkOutline,
            label: ''
        });
        setShowAddModal(true);
    };

    const openScheduleModal = () => {
        setShowAddScheduleModal(true)
    }

    // 添加新分段按钮
    const addNewSegmentButton = () => {
        if (newButtonConfig.value && newButtonConfig.label) {
            // 检查是否已存在相同值的按钮
            if (!segmentButtons.some(btn => btn.value === newButtonConfig.value)) {
                const newButtons = [...segmentButtons, newButtonConfig];
                setSegmentButtons(newButtons);
                setShowAddModal(false);
            } else {
                alert('该分类值已存在，请使用不同的值');
            }
        }
    };

    //添加新的日程
    const addNewSchedule = () => {

    }

    // 删除分段按钮
    const deleteSegmentButton = (value: string) => {
        if (value === 'all') {
            alert('不能删除"全部"分类');
            return;
        }

        const newButtons = segmentButtons.filter(btn => btn.value !== value);
        setSegmentButtons(newButtons);

        // 如果删除的是当前选中的分类，切换到"全部"
        if (selectedType === value) {
            setSelectedType('all');
        }
    };

    return (
        <IonPage>
            <IonHeader>
                <IonToolbar>
                    <IonButtons slot="start">
                        <IonMenuButton />
                    </IonButtons>

                    <IonTitle>我的日程</IonTitle>

                    <IonButtons slot="end">
                        <IonButton>
                            <IonIcon slot="icon-only" icon={ellipsisHorizontal} />
                        </IonButton>
                    </IonButtons>
                </IonToolbar>

                {/* 分类筛选 */}
                <IonToolbar>
                    <IonSegment
                        value={selectedType}
                        onIonChange={e => setSelectedType(e.detail.value as string)}
                        scrollable
                    >
                        {/* 动态生成分段按钮 */}
                        {segmentButtons.map((button) => (
                            <IonSegmentButton
                                key={button.value}
                                value={button.value}
                            >
                                <IonIcon icon={button.icon} />
                                <IonLabel>{button.label}</IonLabel>
                                {button.value !== 'all' && (
                                    <IonButton
                                        slot="end"
                                        fill="clear"
                                        color="danger"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            deleteSegmentButton(button.value);
                                        }}
                                    >
                                        <IonIcon icon={close} size="small" />
                                    </IonButton>
                                )}
                            </IonSegmentButton>
                        ))}

                        {/* 添加新分类按钮 */}
                        <IonSegmentButton
                            value="add"
                            onClick={openAddModal}
                            className="add-segment-button"
                        >
                            <IonIcon icon={add} />
                            <IonLabel>添加</IonLabel>
                        </IonSegmentButton>
                    </IonSegment>
                </IonToolbar>
            </IonHeader>

            <IonContent className="ion-padding">
                {/* 标签筛选 */}
                {/* {allTags.length > 0 && (
                    <div className="tags-container">
                        <IonLabel className="tags-label">标签筛选:</IonLabel>
                        <div className="tags-list">
                            {allTags.map(tag => (
                                <IonButton
                                    key={tag}
                                    size="small"
                                    fill={selectedTags.includes(tag) ? "solid" : "outline"}
                                    color={selectedTags.includes(tag) ? "primary" : "medium"}
                                    onClick={() => toggleTag(tag)}
                                >
                                    {tag}
                                </IonButton>
                            ))}
                        </div>
                    </div>
                )} */}

                {/* 筛选状态提示 */}
                {(searchText || selectedType !== 'all' || selectedTags.length > 0) && (
                    <div className="filter-status">
                        <IonNote>
                            当前筛选:
                            {selectedType !== 'all' && ` 类型: ${selectedType}`}
                            {searchText && ` 搜索: "${searchText}"`}
                            {selectedTags.length > 0 && ` 标签: ${selectedTags.join(', ')}`}
                        </IonNote>
                        <IonButton
                            size="small"
                            fill="clear"
                            color="medium"
                            onClick={clearFilters}
                        >
                            清除筛选
                        </IonButton>
                    </div>
                )}

                {/* 收藏列表 */}
                {filteredFavorites.length > 0 ? (
                    <IonList lines="full" className="favorites-list">
                        {filteredFavorites.map(item => (
                            <IonItem key={item.id} className="favorite-item">
                                <IonThumbnail slot="start">
                                    <img src={item.image} alt={item.title} />
                                </IonThumbnail>

                                <IonLabel>
                                    <h2>{item.title}</h2>
                                    <p>{item.description}</p>
                                    <div className="item-meta">
                                        <IonNote>
                                            <IonIcon icon={time} size="small" />
                                            {item.date}
                                        </IonNote>
                                        <div className="item-tags">
                                            {item.tags.map(tag => (
                                                <IonBadge
                                                    key={tag}
                                                    color="medium"
                                                    className="tag-badge"
                                                >
                                                    {tag}
                                                </IonBadge>
                                            ))}
                                        </div>
                                    </div>
                                </IonLabel>

                                <div slot="end" className="item-actions">
                                    <IonButton
                                        fill="clear"
                                        color={item.isFavorite ? "danger" : "medium"}
                                        onClick={() => toggleFavorite(item.id)}
                                    >
                                        <IonIcon
                                            icon={item.isFavorite ? heart : heartOutline}
                                            slot="icon-only"
                                        />
                                    </IonButton>

                                    <IonButton fill="clear" color="medium">
                                        <IonIcon icon={shareSocial} slot="icon-only" />
                                    </IonButton>
                                </div>
                            </IonItem>
                        ))}
                    </IonList>
                ) : (
                    <div className="empty-state">
                        <IonIcon icon={bookmarkOutline} size="large" color="medium" />
                        <h3>没有收藏内容</h3>
                        <p>您还没有收藏任何内容</p>
                        <IonButton fill="outline" onClick={clearFilters}>
                            查看所有收藏
                        </IonButton>
                    </div>
                )}

                {/* 添加日程按钮 */}
                <IonFab vertical="bottom" horizontal="end" slot="fixed">
                    <IonFabButton color="primary">
                        <IonIcon icon={add} onClick={openScheduleModal} />
                    </IonFabButton>
                </IonFab>
            </IonContent>

            {/* 添加新分类模态框 */}
            <IonModal isOpen={showAddModal} onDidDismiss={() => setShowAddModal(false)}>
                <IonHeader>
                    <IonToolbar>
                        <IonButtons slot="start">
                            <IonButton onClick={() => setShowAddModal(false)}>
                                <IonIcon icon={close} />
                            </IonButton>
                        </IonButtons>
                        <IonTitle>添加新分类</IonTitle>
                        <IonButtons slot="end">
                            <IonButton strong={true} onClick={addNewSegmentButton}>
                                添加
                            </IonButton>
                        </IonButtons>
                    </IonToolbar>
                </IonHeader>
                <IonContent className="ion-padding">
                    <IonItem>
                        <IonLabel position="stacked">分类名称</IonLabel>
                        <IonInput
                            value={newButtonConfig.label}
                            placeholder="输入分类名称"
                            onIonChange={e => setNewButtonConfig({
                                ...newButtonConfig,
                                label: e.detail.value || ''
                            })}
                        />
                    </IonItem>

                    <IonItem>
                        <IonLabel position="stacked">分类值</IonLabel>
                        <IonInput
                            value={newButtonConfig.value}
                            placeholder="输入分类值（唯一标识）"
                            onIonChange={e => setNewButtonConfig({
                                ...newButtonConfig,
                                value: e.detail.value || ''
                            })}
                        />
                    </IonItem>

                    <IonItem>
                        <IonLabel position="stacked">选择图标</IonLabel>
                        <IonSelect
                            value={newButtonConfig.icon}
                            placeholder="选择图标"
                            onIonChange={e => setNewButtonConfig({
                                ...newButtonConfig,
                                icon: e.detail.value
                            })}
                        >
                            {iconOptions.map(option => (
                                <IonSelectOption key={option.value} value={option.value}>
                                    {option.label}
                                </IonSelectOption>
                            ))}
                        </IonSelect>
                    </IonItem>

                    <div className="icon-preview">
                        <IonIcon icon={newButtonConfig.icon} size="large" />
                        <IonNote>图标预览</IonNote>
                    </div>
                </IonContent>
            </IonModal>

            {/*添加日程信息 */}
            <IonModal isOpen={showAddScheduleModal} onDidDismiss={() => setShowAddScheduleModal(false)}>
                <IonHeader>
                    <IonToolbar>
                        <IonButtons slot="start">
                            <IonButton onClick={() => setShowAddScheduleModal(false)}>
                                <IonIcon icon={close} />
                            </IonButton>
                        </IonButtons>
                        <IonTitle>添加日程</IonTitle>
                        <IonButtons slot="end">
                            <IonButton strong={true} onClick={addNewSchedule}>
                                添加
                            </IonButton>
                        </IonButtons>
                    </IonToolbar>
                </IonHeader>
                <IonContent className="ion-padding">
                    <IonItem>
                        <IonLabel position="stacked">输入您的日程内容...</IonLabel>
                        <IonInput
                            value={newButtonConfig.label}
                            placeholder="日程"
                            onIonChange={e => setNewButtonConfig({
                                ...newButtonConfig,
                                label: e.detail.value || ''
                            })}
                        />
                    </IonItem>
                </IonContent>
            </IonModal>

        </IonPage>
    );
};

export default SchedulePage;